package text;

import javax.swing.JEditorPane;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class RelayoutDocumentListener implements DocumentListener {

	private final PageableEditorKit editorKit;

	public RelayoutDocumentListener(PageableEditorKit editorKit) {
		this.editorKit = editorKit;
	}
	
	public void insertUpdate(DocumentEvent e) {
        relayout();
    }

    public void removeUpdate(DocumentEvent e) {
        relayout();
    }

    public void changedUpdate(DocumentEvent e) {
        relayout();
    }

    protected void relayout() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JEditorPane parent=null;
                int lastFooterHeight=0;
                if (editorKit.footer !=null && editorKit.footer.getParent()!=null && editorKit.footer.getParent() instanceof JEditorPane) {
                    parent=(JEditorPane) editorKit.footer.getParent();
                    lastFooterHeight=editorKit.footer.getHeight();
                }
                else if (editorKit.header !=null && editorKit.header.getParent()!=null && editorKit.header.getParent() instanceof JEditorPane) {
                    parent=(JEditorPane)editorKit.header.getParent();
                }
                editorKit.isValidHF = false;
                editorKit.validateHF();
                if (editorKit.footer!=null && lastFooterHeight!=editorKit.footer.getHeight()) {
                    int shift=lastFooterHeight-editorKit.footer.getHeight();
                    editorKit.footer.setLocation(editorKit.footer.getX(),editorKit.footer.getY()+shift);
                }
                ( (SectionView) parent.getUI().getRootView(parent).getView(0)).layout(0, Short.MAX_VALUE);
                parent.repaint();
            }
        });
    }

}
